package com.mxdx.edu.controller;


import java.util.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.mxdx.edu.model.StudentScore;
import com.mxdx.edu.service.IExamLibraryService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.mxdx.edu.common.ApiResult;
import com.mxdx.edu.common.CommonUtils;
import com.mxdx.edu.common.log.AppLogger;
import com.mxdx.edu.enums.ErrorEnums;
import com.mxdx.edu.service.IMaterialService;
import com.mxdx.edu.util.ServletUtil;

/**
 * 辅导资料controller
 * @author howie
 */
@Controller
@RequestMapping(value = "/tutorship")
public class TutorshipController extends BaseController{

	private AppLogger logger = new AppLogger(TutorshipController.class);

//	@Resource
//	private ITutorshipService tutorshipService;
	
	@Resource
	private IMaterialService materialService;

	@Resource
	private IExamLibraryService examLibraryService;

	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/tutorship")
	public ModelAndView tutorship(HttpServletRequest request) {
		logger.entry(ServletUtil.getClientIp(request), "tutorship");
		ApiResult<String> apiResult = new ApiResult<>();
		ModelAndView result = new ModelAndView("/h5/tutorship");
		List<Map<String, Object>> tutorshipList = new ArrayList<>();
		String tutorshipId = ServletUtil.getParameterStr(request, "tutorshipId", "");
		String tutorshipName = ServletUtil.getParameterStr(request, "tutorshipName", "");
		String courseName = ServletUtil.getParameterStr(request, "courseName", "");
		String courseId = ServletUtil.getParameterStr(request, "courseId", "");
		String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
		String token = sessionUtil.getTokenSession(request);
		Map<String, Object> studentMap = (Map<String, Object>) redisUtil.get(token);
		String studentName = CommonUtils.getStrValueFromMap(studentMap, "studentName", "");
		String headPortrait = CommonUtils.getStrValueFromMap(studentMap, "headPortrait", "");
		String studentType = CommonUtils.getStrValueFromMap(studentMap, "studentType", "");
		String mood = CommonUtils.getStrValueFromMap(studentMap, "mood", "");
		try {
			Map<String, Object> findMap = new HashMap<>();
			findMap.put("packetId", tutorshipId);
			tutorshipList = materialService.findListByMap(findMap);
			logger.info(ServletUtil.getClientIp(request));
		} catch (Exception e) {
			dealException(ErrorEnums.SYSTEM_ERROR, e, apiResult, logger);
		}
		result.addObject("tutorshipList", tutorshipList);
		result.addObject("tutorshipName", tutorshipName);
		result.addObject("courseName", courseName);
		result.addObject("courseId", courseId);
		result.addObject("semesterId", semesterId);
		result.addObject("packetId", tutorshipId);
		result.addObject("studentName", studentName);
		result.addObject("headPortrait", headPortrait);
		result.addObject("studentType", studentType);
		result.addObject("mood", mood);
		result.addObject("imageHost", imageHost);
		return result;
	}

	/**
	 * 记录下载资料次数
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/auth/tutorship/download")
	@ResponseBody
	public ApiResult<String> answer(HttpServletRequest request,
									HttpServletResponse response) {
		logger.entry(ServletUtil.getClientIp(request), "download");
		ApiResult<String> result = new ApiResult<>();

		String courseId = ServletUtil.getParameterStr(request, "courseId", "");
		String semesterId = ServletUtil.getParameterStr(request, "semesterId", "");
		String packetId = ServletUtil.getParameterStr(request, "packetId", "");
		String materialId = ServletUtil.getParameterStr(request, "materialId", "0");
		String exceedTerm = ServletUtil.getParameterStr(request, "exceedTerm", "0");

		try {

			Map<String, Object> userMap = getStudentMap(request);
			String studentId = CommonUtils.getStrValueFromMap(userMap, "studentId", "");

			int exits = materialService.materialStudentCountByMap(studentId,courseId,semesterId,materialId);

			materialService.materialStudentDelete(studentId,courseId,semesterId,materialId);

			materialService.materialStudentSave(serialService.generateSerialNum("", 8),studentId,courseId,semesterId,materialId,new Date(),new Date());

			int downLimit = materialService.materialCourseLimitByMap(courseId,packetId);

			//修改下载分数
			StudentScore studentScore = examLibraryService.findStudentScoreByMap(studentId,courseId,semesterId);

			if (studentScore == null || studentScore.getId().length() < 1){
				StudentScore studentScore1 = new StudentScore();

				studentScore1.setId(serialService.generateSerialNum("", 8));
				studentScore1.setStudentId(studentId);
				studentScore1.setCourseId(courseId);
				studentScore1.setSemesterId(semesterId);
				studentScore1.setDownloadNumber(1);
				studentScore1.setRetest(Integer.parseInt(exceedTerm));
				studentScore1.setMaterStatus(1);
				if (downLimit <= 1){
					studentScore1.setMaterStatus(2);
					studentScore1.setMaterScore(100);
				}

				examLibraryService.studentScoreSave(studentScore1);
			}else {
				if (exits < 1){
					studentScore.setDownloadNumber(studentScore.getDownloadNumber() + 1);
				}
				studentScore.setMaterStatus(1);

				if (studentScore.getRetest() != 1) {
					studentScore.setRetest(Integer.parseInt(exceedTerm));
				}
				if (downLimit <= studentScore.getDownloadNumber()){
					studentScore.setMaterStatus(2);
					studentScore.setMaterScore(100);
				}

				examLibraryService.studentScoreUpdate(studentScore);
			}

		} catch (Exception e) {
			super.dealException(ErrorEnums.SYSTEM_ERROR, e, result, logger);
			result.setStatus(ErrorEnums.SYSTEM_ERROR.getCode());
			result.setMessage(ErrorEnums.SYSTEM_ERROR.getDesc());
		}

		return result;
	}

}
